package com.aneliya.view.component.renderer;

import java.awt.Color;

import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

import com.aneliya.formatter.IFormatImpl;
import com.aneliya.formatter.IFormatable;

public class TextItem extends JTextArea implements IDataRenderer,
		IInvalidationRenderer, IFormatable {
	private static final long serialVersionUID = 1L;
	
	private IFormatImpl formatImpl;
	public IFormatImpl getFormatImpl() {
		return formatImpl;
	}
	public void setFormatImpl(IFormatImpl formatImpl) {
		this.formatImpl = formatImpl;
	}
	
	private Boolean isDataChanged = false;
	private Object data;
	public Object getData() {
		return data;
	}
	public void setData(Object value) {
		Object newData = value;
		if (data == null || !data.equals(newData)) {
			data = newData;
			isDataChanged = true;
			invalidateRenderer();
		}
	}
	
	public TextItem() {
		super();
		setLineWrap(true);
		setWrapStyleWord(true);
		setEditable(false);
		setBackground(new Color(0xF0F0F0));
	}

	public void invalidateRenderer() {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				validateRenderer();
			}
		});
		
	}
	
	public void validateRenderer() {
		if (isDataChanged) {
			isDataChanged = false;
			setText(format(data));
			setSelectionStart(0);
			setSelectionEnd(getText().length() - 1);
			validate();
		}
	}
	
	private String format(Object data) {
		return formatImpl.format(data);
	}

}
